package com.cn.bcyp.api.utils;

import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

import com.cn.bcyp.api.config.ExcelDataConfig;
public class SendMailUtil {
	static HelperUtils hu = new HelperUtils();
	static String subject_title = "接口自动化测试结果_" + hu.getNowData(new Date());
	
	public void sendmail(String content, String[] filenames) throws Exception {
		Properties props = new Properties();
		String from = "xxxx@163.com";
		String smtp = "smtp.163.com";
		String servername = "xxxx@163.com";
		String serverpaswd = "123456";

		javax.mail.Session mailSession;
		javax.mail.internet.MimeMessage mimeMsg;

		props = java.lang.System.getProperties();
		props.put("mail.smtp.host", smtp); 
		props.put("mail.smtp.auth", "true");

		Email_Autherticatorbean myEmailAuther = new Email_Autherticatorbean(
				servername, serverpaswd);
		// 设置邮件会话
		mailSession = javax.mail.Session.getInstance(props,
				(Authenticator) myEmailAuther);
		javax.mail.Transport transport = mailSession.getTransport("smtp");

		mimeMsg = new javax.mail.internet.MimeMessage(mailSession);
		if (!from.isEmpty()) {
			InternetAddress sentFrom = new InternetAddress(from);
			mimeMsg.setFrom(sentFrom); // 设置发送人地址
		}
		mimeMsg.setRecipients(Message.RecipientType.TO, ExcelDataConfig.MAIL_SETTO);
		mimeMsg.setRecipients(Message.RecipientType.CC, ExcelDataConfig.MAIL_SETCC);
		mimeMsg.setSubject(subject_title, "UTF-8");

		MimeBodyPart messageBodyPart1 = new MimeBodyPart();
		messageBodyPart1.setContent(content, "text/html;charset=UTF-8");

		Multipart multipart = new MimeMultipart();// 附件传输格式
		multipart.addBodyPart(messageBodyPart1);

		for (int i = 0; i < filenames.length; i++) {
			MimeBodyPart messageBodyPart2 = new MimeBodyPart();
			String filename = filenames[i];
			// 得到数据源
			FileDataSource fds = new FileDataSource(filename);
			// 得到附件本身并至入BodyPart
			messageBodyPart2.setDataHandler(new DataHandler(fds));
			// 得到文件名同样至入BodyPart
			 messageBodyPart2.setFileName(fds.getName());
			multipart.addBodyPart(messageBodyPart2);
		}
		mimeMsg.setContent(multipart);
		mimeMsg.setSentDate(new Date());
		mimeMsg.saveChanges();
		transport.send(mimeMsg);
		transport.close();
	}
	
	
}
